#include "scroll.h"

#include <math.h>

#include "sdlutil.hpp"

Scroll::Scroll(IElement* parent, SDL_Surface* surf,ScrollOrientation orient = Horizontal)
	:IElement(parent, surf)
	,orientation_(orient)
	,cur_(0)
{
	length_ = size_.Get(0);
	recalcBar();
	curBarColor_ = UI_FORE_COLOR;
}


Scroll::~Scroll()
{
}

void Scroll::recalcBar()
{
	int rlen = 1;
	if(orientation_ == Vertical)
	{
		rlen = size_.Get(1);
	}else if(orientation_ == Horizontal)
	{
		rlen = size_.Get(0);
	}
	float mult = ((float)(rlen)/ (length_));
	barLen_ = (int)floor( mult * rlen ) ;

	float mult2 = ((float)(rlen - 6 -barLen_)/ (length_));
	barStart_ = (cur_ / mult2 - (barLen_/2));
}

void Scroll::SetLength(int val)
{
	length_ = val;
	recalcBar();
}

void Scroll::SetPos(int val)
{
	cur_ = val;
	recalcBar();
}


void Scroll::update()
{

}

void Scroll::render(int x, int y)
{
	int xl = position_.Get(0);
	int yl = position_.Get(1);
	int wl = size_.Get(0);
	int hl = size_.Get(1);

	draw_rect(surface_, xl, yl,  wl, hl, UI_BORD_COLOR,false);
	if(orientation_ == Vertical)
	{
		draw_rect(surface_, xl+3, yl + barStart_,  wl-6, barLen_, curBarColor_,true);
	}else if(orientation_ == Horizontal)
	{
		draw_rect(surface_, x+barStart_, yl + 3,  barLen_, hl-6, curBarColor_,true);
	}
}

bool Scroll::mouseUp(int x, int y, Uint8 button)
{
	Vec<int,2> cpos;
	cpos.Set(0,x);
	cpos.Set(1,y);
	Vec<int,2> p1;
	Vec<int,2> p2;

	if(orientation_ == Vertical)
	{	
		p1.Set(0,position_.Get(0));
		p1.Set(1,size_.Get(1)+3+barStart_);

		p2.Set(0,size_.Get(0));
		p2.Set(1,size_.Get(1)+3+barStart_+ barLen_);
	}else if(orientation_ == Horizontal)
	{
		p1.Set(0,position_.Get(0)+3+barStart_);
		p1.Set(1,position_.Get(1));

		p2.Set(0,size_.Get(0)+3+barStart_+ barLen_);
		p2.Set(1,size_.Get(1));
	}

	if(cpos.isInRect(p1,p2) == true)
	{
		curBarColor_ = UI_FORE_COLOR;

	}
	return true;
}

bool Scroll::mouseDown(int x, int y, Uint8 button)
{
	Vec<int,2> cpos;
	cpos.Set(0,x);
	cpos.Set(1,y);
	Vec<int,2> p1;
	Vec<int,2> p2;

	if(orientation_ == Vertical)
	{	
		p1.Set(0,position_.Get(0));
		p1.Set(1,size_.Get(1)+3+barStart_);

		p2.Set(0,size_.Get(0));
		p2.Set(1,size_.Get(1)+3+barStart_+ barLen_);
	}else if(orientation_ == Horizontal)
	{
		p1.Set(0,position_.Get(0)+3+barStart_);
		p1.Set(1,position_.Get(1));

		p2.Set(0,size_.Get(0)+3+barStart_+ barLen_);
		p2.Set(1,size_.Get(1));
	}

	if(cpos.isInRect(p1,p2) == true)
	{
		curBarColor_ = UI_SEL_COLOR;

	}
	return true;
}

void Scroll::onResize()
{
	recalcBar();
}

void Scroll::onMove()
{
	recalcBar();
}
